import cv2
import numpy as np

# 加载车牌信息(imread(图片路径,读取方式)  读取方式==0 灰度图)
img = cv2.imread("./img/panels/product/XXN18.jpg")
# 原图的高宽：
img_h, img_w, _ = img.shape
# 灰度图
img_panel_gray = cv2.imread("./img/panels/product/XXN18.jpg", 0)
# 取出黑白的二值化图
_, img_panel_binary = cv2.threshold(img_panel_gray, 127, 255, cv2.THRESH_BINARY)
# 针对二值化的图进行膨胀
kernel = np.ones((5, 5))
img_panel_binary = cv2.dilate(img_panel_binary, kernel)
# 寻找黑白图中的轮廓(外轮廓 RETR_EXTREL) --> (内轮廓 RETR_LIST)
contours, _ = cv2.findContours(img_panel_binary, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
# 定义一个存放坐标值的列表
num_list = []
# 循环所有的轮廓信息，并标注出来
for contour in contours:
    # 找出所有白色区域的最大外接矩形
    x, y, w, h = cv2.boundingRect(contour)
    if 20 // 14 <= w <= img_w // 7 and img_h // 2 <= h < img_h:
        # 针对字体较小的区域
        if w * h < 3000:
            x -= 15
            w += 30
        # 绘制外接矩形
        cv2.rectangle(img, (x, y), (x + w, y + h), color=(0, 0, 255), thickness=2)
        # 存放左上角坐标和右下角坐标
        num_list.append([x, y, x + w, y + h])

# 切出所有的关于车牌信息的部分
# count = 0
# for x1, y1, x2, y2 in num_list:
#     chr_img = img_panel_binary[y1:y2, x1:x2]
#     # 显示切图
#     cv2.imshow(f"char{count}", chr_img)
#     count += 1

# 显示车牌的信息
# cv2.imshow("panel", img_panel)
# 展示黑白二值化图
# cv2.imshow("img_panel_binary", img_panel_binary)
# 显示原图
cv2.imshow("img", img)
cv2.waitKey(0)
